package com.sx.pipeline.ui.task.participate

import android.app.Application
import android.net.Uri
import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.http.CommonObserverNull
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.config.ParticipateTaskType
import com.sx.pipeline.app.event.RefreshEvent
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.repos.http.req.DealTaskDTO
import com.sx.pipeline.repos.http.res.Ipage
import com.sx.pipeline.repos.http.res.ReleaseTaskVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.rong.imkit.RongIM
import io.rong.imlib.model.Conversation

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: TODO
 */
class ParticipateTaskVM(app: Application) : CYBaseViewModel(app) {

    /**
     * 获取我参与的任务类型标题
     */
    fun getReleaseTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.txt_upcoming))
        tabs.add(getApplication<Application>().getString(R.string.txt_in_progress))
        tabs.add(getApplication<Application>().getString(R.string.txt_completed))
        tabs.add(getApplication<Application>().getString(R.string.txt_over))
        return tabs
    }


    /**
     * 获取我参与的类型id
     */
    fun getParticipateTabsId(): List<Int> {
        val tabs = mutableListOf<Int>()
        tabs.add(ParticipateTaskType.AGENCY.code)
        tabs.add(ParticipateTaskType.IN_PROGRESS.code)
        tabs.add(ParticipateTaskType.COMPLETED.code)
        tabs.add(ParticipateTaskType.OVER.code)
        return tabs
    }

    /**
     * 获取我参与的任务列表
     */
    var status = 0
    var page = 1
    val participateTaskListEvent: SingleLiveEvent<List<ReleaseTaskVo>> = SingleLiveEvent()
    fun takePartTaskList(status: Int) {
        addSubscribe(
            mModel.takePartTaskList(status, page)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseTaskVo>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Ipage<ReleaseTaskVo>) {
                        participateTaskListEvent.postValue(result.records)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }


    /**
     * 删除任务
     */
    fun getRemoveTask(id: Int) {
        addSubscribe(
            mModel.getRemoveTask(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("任务删除成功")
                        takePartTaskList(status)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 处理任务
     * @param
     */
    val dealSuccessEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun dealWithTask(
        pushType: Int,
        orderId: Int,
        contact: String,
        desc: String,
        imageUrls: String,
        milieuDesc: String,
        needNeed: String,
        hasGroup: String,
    ) {
        val dto =
            DealTaskDTO(pushType, orderId, contact, desc, imageUrls, hasGroup, milieuDesc, needNeed)
        addSubscribe(
            mModel.dealWithTask(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("提交成功")
                        //通知列表刷新
                        RxBus.getDefault().post(RefreshEvent())
                        finish()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    //加入群聊
    fun requestJoinGroup(id: Int, groupId: String) {
        addSubscribe(
            mModel.requestJoinGroup(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(object : CommonObserverNull<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any?) {
                        ToastUtils.showShort("加入群聊成功")
                        getRongGroupListOne{
                            Log.i("requestJoinGroup", "onResult: "+groupId)
                            ARouter.getInstance().build(RoutePath.Chat.CHAT_DETAIL)
                                .withString("targetId", groupId)
                                .withString("ConversationType",
                                    Conversation.ConversationType.GROUP.toString())
                                .navigation()
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        if(code==201){
                            getRongGroupListOne{
                                ARouter.getInstance().build(RoutePath.Chat.CHAT_DETAIL)
                                    .withString("targetId", groupId)
                                    .withString("ConversationType",
                                        Conversation.ConversationType.GROUP.toString())
                                    .navigation()
                            }
                        }else{
                            ToastUtils.showShort(msg)
                        }
                    }
                })

        )
    }

    fun getRongGroupListOne(refreshSuccess:(()->Unit)) {
        addSubscribe(
            mModel.getRongGroupList()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<RongGroupVO>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<RongGroupVO>) {

                        refreshRongGroupInfo(result,refreshSuccess)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )

    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>,refreshSuccess:(()->Unit)) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
        refreshSuccess.invoke()
    }

}